setwd("E://OneDrive//1-教学//科技论文写作//课件//课上使用的文档//2.9.5-科研绘图//热点图")

# 读取数据
df <- read.delim("https://www.bioladder.cn/shiny/zyp/demoData/heatmap/data.heatmap.txt",row.names = 1) 
df #矩阵数据

# 归一化
dfNormalize <- t(scale(t(df))) %>% as.data.frame() #标准化处理成均值为0，标准差为1的矩阵。


# 转化为ggplot2格式的数据类型。长数据
dfLong = dfNormalize %>%
  rownames_to_column("Gene") %>%
  pivot_longer(-1,names_to = "Sample",values_to = "Value")
dfLong #每个数据对应一对坐标xy，在同行


library(ggplot2)


p <- ggplot(dfLong)+
  geom_raster(aes(x=Sample, y=Gene, fill=Value))+ 
  scale_fill_gradient2(low="#0000ff", high="#ff0000", mid="#ffffff")+
  scale_y_discrete(position="right") +    #y轴放右边
  theme_minimal()+
  theme(panel.grid.major=element_blank()) #主网格线为空
p


# 添加分组条带

library(aplot)   #拼图

# X轴(单条带例子)
dfSample <- read.delim("https://www.bioladder.cn/shiny/zyp/demoData/heatmap/sample.class.txt")
dfSample <- mutate(dfSample, Y = "Group") #数据格式转换
pX <- ggplot(dfSample)+
  geom_tile(aes(x = X,y = Y,fill = Group)) +  #矩形瓦片图
  theme_void()+
  labs(fill = "Group")

# y轴(双条带例子)
dfGene  <-  read.delim("https://www.bioladder.cn/shiny/zyp/demoData/heatmap/gene.class.txt") 
dfGene <- pivot_longer(dfGene, -1) #数据格式转换
pY <- ggplot(dfGene)+
  geom_tile(aes(x = name, y = X, fill = value)) +
  theme_void()+
  labs(fill = "Class")
pY

# 拼图
p1.1 <- insert_top(p, pX, height = .05)
p1 <- insert_left(p1.1, pY, width = .09)
p1


#聚类树
if (!requireNamespace("ggtree", quietly = TRUE)){
  if (!requireNamespace("BiocManager", quietly = TRUE)){
    install.packages("BiocManager")
  }
  BiocManager::install("ggtree")
}    #ggtree包用于画聚类树，需使用BiocManager包管理安装

library(ggtree)  #聚类
distsY <- dist(dfNormalize, method = "euclidean")
     #计算距离矩阵，默认method = "euclidean"计算欧氏距离
hcY <- hclust(dists, method = "complete")
     # 进行层次聚类，聚类算法method = "ward.D", "ward.D2", "single", "complete", "average" (= UPGMA), "mcquitty" (= WPGMA), "median" (= WPGMC) or "centroid" (= UPGMC).
phY <- ggtree(hcY, layout="rectangular",branch.length="none")
     #绘制系统发育树（聚类树）


hcX <- hclust(dist(t(dfNormalize), method = "euclidean"), method = "complete")
     #xy转置后的聚类分析（多步合并）

phX <- ggtree(hcX, layout="rectangular",branch.length="none")+ #聚类树
  layout_dendrogram()                                          #转置
phX

#拼图
p2.1 <- insert_top(p, pX, height = .05)
p2.2 <- insert_left(p2.1, pY, width = .09)
p2.3 <- insert_left(p2.2, phY,width=.2)
p2 <- insert_top(p2.3, phX,height=.2)
p2
